package com.dj.ms.event;

import cn.hutool.core.util.ObjectUtil;
import com.dj.ms.event.support.EventRetryTaskDataManager;
import com.dj.ms.event.support.EventRetryTaskRepository;
import com.dj.ms.support.SpringBeanFactoryUtils;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.Map;

/**
 * <br>
 * <p>异步事件监听器</p>
 *
 * <br>
 *
 * @author ZJG
 * @version 1.0
 * @date 2021/7/26 下午6:51
 */
public interface AsyncListener {

    /**
     * 注册重试任务数据管理器
     * @return  EventRetryTaskRepository
     */
    EventRetryTaskRepository registerReRetryTaskRepository();

    /**
     * 注册异步事件
     */
    @PostConstruct
    default void register() {
        Map<String, AsyncListener> beansOfTypes = SpringBeanFactoryUtils.getBeansOfType(AsyncListener.class);
        Collection<AsyncListener> listeners = Lists.newLinkedList(beansOfTypes.values());
        if (!CollectionUtils.isEmpty(listeners)) {
            listeners.stream().forEach(listener -> {
                Class<? extends AsyncListener> clzz = listener.getClass();
                EventRetryTaskRepository eventRetryTaskRepository = this.registerReRetryTaskRepository();
                if (ObjectUtil.isNotNull(eventRetryTaskRepository)) {
                    EventRetryTaskDataManager.register(clzz.getCanonicalName(), eventRetryTaskRepository);
                }
            });
        }
        EventBusHandler.registerAsync(this);
    }

}
